<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" width="600px" destroyOnClose showFooter>
    <BasicForm @register="registerForm"/>
    <BasicTree
      ref="treeRef"
      checkable
      toolbar
      :toolbarOptions="toolbarOptions"
      :treeData="state.treeData"
      :checkedKeys="state.checkedKeys"
      :selectedKeys="state.selectedKeys"
      :clickRowToExpand="true"
      :checkStrictly="true"
      :fieldNames="{ key: 'id' }"
      search
      :defaultExpandLevel="2"
      title=""
      @select="onTreeNodeSelect"
    >
      <template #title="{ title, menuType, apiActions }">
        <span>{{ title }}</span>
        <div v-if="apiActions.length > 0">
          <Tooltip placement="top">
            <template #title>
              <span v-for="item in apiActions" :key="item">
                {{ item }} <br/>
              </span>
            </template>
            <Icon icon="i-ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
          </Tooltip>
        
        </div>
        
      </template>
    </BasicTree>

    <!--右下角按钮-->
    <template #footer>
      <PopConfirmButton title="确定放弃编辑？" @confirm="closeDrawer" okText="确定" cancelText="取消">取消</PopConfirmButton>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </template>
    <!-- <PermissionDescDrawer @register="registerDrawer1" @success="handleLoadTree"/> -->
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted, toRaw } from "vue"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { BasicTree, TreeItem, TreeActionType, ToolbarEnum } from "/@/components/Tree"
  import { Tooltip } from "ant-design-vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import * as permPolicyApi from '/@/api/iam/permPolicy';
  import { PopConfirmButton } from "/@/components/Button"
  import { menuInputFormSchemas } from './data';
  // import PermissionDescDrawer from "./PermissionDescDrawer.vue"
  import * as menuApi from '/@/api/iam/menu'
  import * as treeUtils from '/@/utils/helper/treeHelper'
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Icon } from "/@/components/Icon"
  const { createMessage } = useMessage()

  const toolbarOptions = ref<ToolbarEnum[]>([ToolbarEnum.EXPAND_ALL, ToolbarEnum.UN_EXPAND_ALL, ToolbarEnum.SELECT_ALL, ToolbarEnum.UN_SELECT_ALL])

  const emit = defineEmits(["register"])

  interface State {
    // 树的信息
    treeData: TreeItem[]
    flatTreeData: TreeItem[]
    // 树的全部节点信息
    allTreeKeys: any[]
    //树的选择节点信息
    checkedKeys: any[]
    halfCheckedKeys: any[]
    defaultCheckedKeys: any[]
    //树的选中的节点信息
    selectedKeys: any[]
    name?: any
    apiNamespaceCode?: any
    // 策略id
    id?: any
    // 策略配置
    policyContent: any
  }

  const state = ref<State>({
    treeData: [],
    allTreeKeys: [],
    flatTreeData: [],
    checkedKeys: [],
    halfCheckedKeys: [],
    defaultCheckedKeys: [],
    selectedKeys: [],
    name: '',
    apiNamespaceCode: null,
    policyContent: []
  })

  const title = computed(() => `控制台菜单权限策略 ${state.value.name}`)
  const treeRef = ref<TreeActionType>()
  const loading = ref(false)
  const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
    labelWidth: 90,
    schemas: menuInputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    try {
      setDrawerProps({ loading: true })
      await reset()
      state.value.apiNamespaceCode = data.apiNamespaceCode
      const result = await permPolicyApi.getPermissionPolicy({ apiNamespaceCode: data.apiNamespaceCode, id: data.record.id })
      console.log('result', result)
      state.value = { ...result, apiNamespaceCode: data.apiNamespaceCode }
      setFieldsValue({ ...state.value})
      await handleLoadTree()
    } catch(ex) {
      console.error(ex)
      setDrawerProps({ loading: false })
    }
  })


  // function onCheck(checkedKeys, e: { checked, checkedNodes, node, event}) {
  //   console.log('check-menu', checkedKeys, e)
  //   state.value.halfCheckedKeys = checkedKeys.halfChecked || []
  //   state.value.checkedKeys = checkedKeys.checked || []
  // }

  async function handleLoadTree() {
    loading.value = true
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      //初始化角色菜单数据
      state.value.treeData = await menuApi.listMenu({
        apiNamespaceCode: state.value.apiNamespaceCode,
      })

      state.value.flatTreeData = treeUtils.treeToList(state.value.treeData)
      state.value.allTreeKeys = state.value.treeData.map((e) => e.id)

      state.value.checkedKeys = state.value.policyContent?.statement.map((e) => e.resourceId)
      state.value.defaultCheckedKeys = state.value.policyContent?.statement.map((e) => e.resourceId)
    } finally {
      loading.value = false
      setDrawerProps({ loading: false })
    }
  }

  function onTreeNodeSelect(key, { node }) {
    console.log("select-menu", key, node)
    if (key && key.length > 0) {
      state.value.selectedKeys = key
    }
    const menuId = toRaw(state.value.selectedKeys)[0]
    // openPermissionDescDrawer(true, { 
    //   menuId: menuId, 
    //   roleId: toRaw(state.value.subjectId), 
    //   permPolicyList: node.permPolicyList 
    // })
  }

  async function reset() {
    await resetFields();
    state.value.treeData = []
    state.value.allTreeKeys = []
    state.value.checkedKeys = []
    state.value.defaultCheckedKeys = []
    state.value.selectedKeys = []
    state.value.name = null
  }

  function getTree() {
    const tree = unref(treeRef)
    if (!tree) {
      throw new Error("tree is null!")
    }
    return tree
  }

  async function handleSubmit(exit) {
    setDrawerProps({ confirmLoading: false, loading: true })
    const { id, } = unref(state)
    let formValues = await validate();
    try {
      let params = {
        id: id,
        apiNamespaceCode: state.value.apiNamespaceCode,
        // @ts-ignore
        ...formValues,
        // @ts-ignore
        resourceIds: toRaw(treeRef.value?.getCheckedKeys()),
      }

      loading.value = true
      await permPolicyApi.updateMenuPermissionPolicy(params)
      exit && closeDrawer()
      createMessage.success("操作成功")
    } finally {
      loading.value = false
      setDrawerProps({ confirmLoading: false, loading: false })
    }
  }
</script>
